import {ajax,base,pageTo} from 'nc-lightapp-front';
import requestApi from '../requestApi';
import {updataFormData, updatacardTableData} from 'ssccommon/utils/changePageData';
import { zzhllxLogic } from '../utils';

import _ from 'lodash-es'
const {NCMessage} = base;

export default function afterEvent(props,moduleId,key,value,changedrows,index,attr) {

    let paramdata = {};
    let moduleid =moduleId =="head"?"headform":moduleId;
    let pagecode = props.getSearchParam("p");
    let bodys = Object.values(window.presetVar.body);
    let bodyarr = [];
    let hideTable = this.state.hideTables;
    bodys && bodys.length && bodys.forEach((one)=>{
        if(hideTable && hideTable.indexOf(one)<0){
            bodyarr[bodyarr.length] = one;
        }
    })
    if(moduleid=="headform"){
        let billdata = props.createExtCardData(window.presetVar.pageId, 'head',bodyarr);
        requestApi.handleLoadDataResDada(props.meta.getMeta(), {data:billdata},props);
    }
    paramdata = {
        "value":value,
        "tableid":moduleid,
        "field":key,
        "uistate":props.getUrlParam("status"),
        "tradetype":props.getUrlParam("tradetype")||window.presetVar.tradetype,
        "oldvalue":'',
        "pagecode":window.presetVar.pagecode,
        "appcode":window.presetVar.appcode
    }
    if(moduleid!="headform"){
        paramdata.changeRowId=changedrows[0].rowid;
    }else{
        paramdata.value = value.value;
    }    
    switch(moduleId) {
        case 'head' :
            switch(key) {
                case 'pk_org'://表头财务组织
                case 'pk_org_v'://表头借款单位
                case 'pk_pcorg': // 利润中心
                case 'djrq'://表头单据日期
                case 'bzbm'://表头币种
                case 'bbhl'://表头本币汇率
                case 'dwbm_v'://表头借款报销人单位版本
                case 'dwbm'://表头借款报销人单位
                case 'fydwbm_v'://表头费用承担单位版本
                case 'fydwbm'://表头费用承担单位
                case 'pk_payorg_v'://表头支付单位版本
                case 'pk_payorg'://表头支付单位
                case 'deptid_v':// 表头报销人部门版本
                case 'deptid':// 表头报销人部门
                case 'fydeptid_v':// 表头费用承担部门版本
                case 'fydeptid':// 表头费用承担部门
                case "jkbxr"://借款报销人
                case "receiver"://表头收款人
                case "szxmid"://表头收支项目
                case "skyhzh"://表头个人银行账户
                case "jobid"://表头项目
                case "freecust"://散户
                case "custaccount"://表头客商银行账户
                case "paytarget"://表头收款对象
                case "hbbm"://表头供应商
                case "customer"://表头客户
                case "zzhllyrq"://组织汇率来源日期
                case "zzhllx"://组织汇率类型
                case "hbbm_v"://表头供应商
                case "customer_v"://表头客户
                  
                    //表头修改后数据后台需要的结构， 一主一子  一主多子
                    if (key === 'paytarget') {
                        if (value.value == '0') {
                            props.form.setFormItemsDisabled('head', {
                                hbbm: true,
                                customer: true,
                                hbbm_v: true,
                                customer_v: true,
                                custaccount: true,
                                receiver: false,
                                freecust: true
                            });
                        } else if (value.value == '1') {
                            props.form.setFormItemsDisabled('head', {
                                receiver: true,
                                customer: true,
                                hbbm: false,
                                customer_v: true,
                                hbbm_v: false,
                                custaccount: false,
                                freecust: false
                            });
                        } else if (value.value == '2') {
                            props.form.setFormItemsDisabled('head', {
                                hbbm: true,
                                hbbm_v: true,
                                receiver: true,
                                customer: false,
                                customer_v: false,
                                custaccount: false,
                                freecust: true
                            });
                        }
                    }
                    let billdata = props.createHeadAfterEventData(pageTo.getSearchParam("p"), "head", bodyarr, moduleId, key, value);
                    billdata.card.head.userjson = JSON.stringify(paramdata);
                    billdata.templetid =props.meta.getMeta().pageid;
	                // BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
                    requestApi.valueChange({
                        data: billdata.card,
                        success: (data)=> {

                            // 设置表头数据
                            updataFormData(props, 'head', requestApi.filterDatas(data.head['head']));
                            // 设置表体数据
                            bodyarr.forEach((item) =>{
                                setTimeout(()=>{
                                    updatacardTableData(props, item, requestApi.filterDatas(data.bodys[item]));
                                },0);
                            })
                            // BTM 性能优化，变更页面数据更新方法
                            let org_currinfo = props.form.getFormItemsValue('head','bbhl');
                            let bzbmValue = props.form.getFormItemsValue(presetVar.head.head1,'bzbm');
                            if(key=='bzbm' &&org_currinfo.value!=undefined && org_currinfo.value!=null && parseFloat(org_currinfo.value) == parseFloat(1) )
                            {
                                props.form.setFormItemsDisabled('head',{'bbhl':true});
                            }else{
                                props.form.setFormItemsDisabled('head',{'bbhl':false});
                            }

                            //表头值变化后为表体元数据赋值
                            let headrows = data.head['head'].rows[0].values;
                            let headtrr = ['pk_org','szxmid','pk_pcorg','pk_pcorg_v','pk_checkele','jobid','projecttask','pk_resacostcenter','pk_proline','pk_brand','fctno','bzbm','tax_rate','bbhl','groupbbhl','globalbbhl','receiver','freecust','jkbxr','dwbm','skyhzh','custaccount','customer','deptid','paytarget','hbbm'];
                            let cshare_detail = ['assume_org','assume_dept','pk_iobsclass'];//'fydwbm','fydeptid',
                            let metas  = props.meta.getMeta();
                            //Object.keys(presetVar.body).forEach((bodyindex) =>{
                            for (let bodyname in metas.gridrelation) {
                               // let bodyname = presetVar.body[bodyindex];
                                if(metas[bodyname].items!=undefined&&metas[bodyname].items!=null&&bodyname!='er_bxcontrast'&&bodyname!='accrued_verify'&&bodyname!='head'){
                                    metas[bodyname].items.forEach((item) => {
                                        if (headtrr.indexOf(item.attrcode) > -1 || cshare_detail.indexOf(item.attrcode) > -1) {
                                            let keycode = '';
                                            if(item.attrcode=='assume_org'){
                                                keycode = 'fydwbm';
                                            }else if(item.attrcode=='assume_dept'){
                                                keycode = 'fydwbm';
                                            }else if(item.attrcode=='pk_iobsclass'){
                                                keycode = 'szxmid';
                                            }else{
                                                keycode = item.attrcode;
                                            }
                                            if(headrows[keycode]!=undefined && headrows[keycode].value!=undefined){
                                                let valuecode = headrows[keycode].value==undefined?'':headrows[keycode].value;
                                                let displaycode = valuecode==''?'':(headrows[keycode].display==undefined||headrows[keycode].display==''?valuecode:headrows[keycode].display)
                                                let initialvalue={
                                                    value: valuecode,
                                                    display: displaycode
                                                }
                                                item.initialvalue =initialvalue;
                                            }
                                        }
                                    });
                                }
                            };
                        }
                    })
                    let currentrow_bzbm = props.form.getFormItemsValue(presetVar.head.head1,'bzbm');
                    // 新增汇率适配逻辑
                    let rate_category =  props.form.getFormItemsValue(presetVar.head.head1,'zzhllx.rate_category'); 
                    zzhllxLogic(currentrow_bzbm,rate_category,'head',props)
                    break;
                default:
                    break;
            }
            //编辑后事件控制字段可编辑性需要放到valuechange之后
            let bbhlFlag = props.form.getFormItemsDisabled('head', 'bbhl'); //表头本币汇率编辑性
            let zzhllxFlag = props.form.getFormItemsDisabled('head', 'zzhllx'); //表头本币汇率类型编辑性
            let zzhllyrqFlag = props.form.getFormItemsDisabled('head', 'zzhllyrq'); //表头本币汇率日期编辑性
            bodyarr.forEach((tablecode)=>{
            
                let allrows = props.cardTable.getAllRows(tablecode)
                if (allrows){
                    allrows.forEach((row) => {
                        // let currentrow_paytarget = props.cardTable.getValByKeyAndRowId(tablecode, row.rowid, 'paytarget')
                        let currentrow_paytarget = props.form.getFormItemsValue('head','paytarget');
                        if (currentrow_paytarget){
                            let currentrow_paytargetvalue = currentrow_paytarget.value
                                //控制表体收款对象相关字段的可编辑性
                            let editablekeys = []
                            let uneditablekeys = []
                            if ("0" == currentrow_paytargetvalue){
                                editablekeys = ['receiver','skyhzh']
                                uneditablekeys = ['hbbm','hbbm_v','customer','customer_v','custaccount']
                            }else if("1" == currentrow_paytargetvalue){
                                editablekeys = ['hbbm','hbbm_v','custaccount']
                                uneditablekeys = ['receiver','skyhzh','customer','customer_v']
                            }else if("2" == currentrow_paytargetvalue){
                                editablekeys = ['customer','customer_v','custaccount']
                                uneditablekeys = ['receiver','skyhzh','hbbm','hbbm_v']
                            }
                            props.cardTable.setEditableByRowId(tablecode, row.rowid, editablekeys, true)
                            props.cardTable.setEditableByRowId(tablecode, row.rowid, uneditablekeys, false)
                        }
                        // 表头中本币种、汇率类型更改后，表体中本币汇率、汇率类型、汇率来源日期需同时控制其编辑性
                        let editkeys = []
                        let unedikeys = []
                        bbhlFlag ? unedikeys.push('bbhl') : editkeys.push('bbhl')
                        zzhllxFlag ? unedikeys.push('zzhllx') : editkeys.push('zzhllx')
                        zzhllyrqFlag ? unedikeys.push('zzhllyrq') : editkeys.push('zzhllyrq')
                        props.cardTable.setEditableByRowId(tablecode, row.rowid, editkeys, true)
                        props.cardTable.setEditableByRowId(tablecode, row.rowid, unedikeys, false)
                    })
                }
            })   
            break;
        default:
            //表体字段处理
            //满足报销标准核心控制项字段影响因素
            if(key!=window.presetVar.showitemkey 
                && ( (window.presetVar.reimsrc!=null && window.presetVar.reimsrc.length>0 && window.presetVar.reimsrc.includes(key))
                   ||  (window.presetVar.reimruleitemkeys!=null && window.presetVar.reimruleitemkeys.length>0 && window.presetVar.reimruleitemkeys.indexOf(key) != -1) )
            ) {
                //清空当前行报销标准的值，以重新获取
                if(changedrows[0].newvalue.value==changedrows[0].oldvalue.value){
                    break;
                }
                props.cardTable.setValByKeyAndRowId(presetVar.body.body1,changedrows[0].rowid,window.presetVar.showitemkey,{value:0.00, display: 0.00});

                let billdata = props.createHeadAfterEventData(pageTo.getSearchParam("p"), "head", bodyarr, moduleId, key, value);
                paramdata.checkrule='true'
                if(value.value==undefined||value.value==null){
                    paramdata.value = changedrows[0].newvalue.value;
                }
                billdata.card.head.userjson = JSON.stringify(paramdata);
                billdata.templetid =props.meta.getMeta().pageid;
                // let send_headdata = {billdata,paramdata};
                // // TOP NCCLOUD-91597 校验报销标准取模板时需要使用模板ID chengwbc ADD
	            // send_headdata.templateid = props.meta.getMeta().pageid;
	            // BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
                requestApi.valueChange({
                    data: billdata.card,
                    success: (data)=> {
                        // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                        // //设置表头数据
                        // props.form.setAllFormValue({['head']: requestApi.filterDatas(data.head['head'])});
                        // //设置表体数据
                        // props.cardTable.setTableData(moduleid, requestApi.filterDatas(data.bodys[moduleid]));
                        // 设置表头数据
                        updataFormData(props, 'head', requestApi.filterDatas(data.head['head']));
                        // 设置表体数据
                        updatacardTableData(props, moduleid, requestApi.filterDatas(data.bodys[moduleid]));
                        // BTM 性能优化，变更页面数据更新方法
                        let billdatas = props.createExtCardData(window.presetVar.pageId, 'head',bodyarr);
                        requestApi.handleLoadDataResDada(props.meta.getMeta(), {data:billdatas},props);
                        props.cardTable.setTableDataWithResetInitValue(moduleid, requestApi.filterDatas(data.bodys[moduleid]));
                    }
                })
                return;//满足报销标准核心控制项字段影响因素的字段直接返回
            }
            switch (key){
                case 'pk_org'://表头财务组织
                case 'pk_pcorg': // 利润中心
                case 'djrq'://表头单据日期
                case 'bzbm'://表头币种
                case 'bbhl'://表头本币汇率
                case 'dwbm_v'://表头借款报销人单位版本
                case 'dwbm'://表头借款报销人单位
                case 'fydwbm_v'://表头费用承担单位版本
                case 'fydwbm'://表头费用承担单位
                case 'pk_payorg_v'://表头支付单位版本
                case 'pk_payorg'://表头支付单位
                case 'deptid_v':// 表头报销人部门版本
                case 'deptid':// 表头报销人部门
                case 'fydeptid_v':// 表头费用承担部门版本
                case 'fydeptid':// 表头费用承担部门
                case "jkbxr"://借款报销人
                case "receiver"://表头收款人
                case "szxmid"://表头收支项目
                case "skyhzh"://表头个人银行账户
                case "jobid"://表头项目
                case "freecust"://散户
                case "custaccount"://表头客商银行账户
                case "paytarget"://表头收款对象
                case "hbbm"://表头供应商
                case "customer"://表头客户
                case "customer_v":
                case "hbbm_v":
                case  "vat_amount"://表体含税金额
                case 'tni_amount'://表体不含税金额
		        case 'amount'://表体金额
		        case 'ybje'://原币金额
		        case 'bbje'://本币金额
                case "zzhllyrq"://组织汇率来源日期
                case "zzhllx"://组织汇率类型
                    //let billdata = props.createHeadAfterEventData('20110ETEA_2641_IWEB', "head",[moduleid], moduleId, key, value);
                   // let data = props.createGridAfterEventData('20521030', moduleid, moduleId, key, changedrows);
                   // let billdata = props.createBodyAfterEventData('20110ETEA_2641_IWEB', 'head', moduleid, moduleId, key, changedrows);
                    if(changedrows[0].newvalue.value==changedrows[0].oldvalue.value){
                        break;
                    }
                    let billdata = props.createHeadAfterEventData(pageTo.getSearchParam("p"), "head", bodyarr, moduleId, key, value);
                    console.log('表头字段change后表头标题数据结构：', billdata);
                    if(value.value==undefined||value.value==null){
                        paramdata.value = changedrows[0].newvalue.value;
                    }

                    for(var i=0,flag=true,len=billdata.card.bodys.jk_busitem.rows.length;i<len;flag ? i++ : i){
                        if(billdata.card.bodys.jk_busitem.rows[i] != undefined && billdata.card.bodys.jk_busitem.rows[i].status == 3){
                            billdata.card.bodys.jk_busitem.rows.splice(i,1);
                            flag = false;
                        }else{
                            flag = true;
                        }
                    }
                    billdata.card.head.userjson = JSON.stringify(paramdata);
                    billdata.templetid =props.meta.getMeta().pageid;
                    console.log('表头字段change后表头标题数据结构：', billdata);
                    // let send_headdata = {billdata,paramdata};
                    // // TOP NCCLOUD-91597 校验报销标准取模板时需要使用模板ID chengwbc ADD
	                // send_headdata.templateid = props.meta.getMeta().pageid;
	                // BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
                    requestApi.valueChange({
                        data: billdata.card,
                        success: (data)=> {
                            // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                            // //设置表头数据
                            // props.form.setAllFormValue({['head']: requestApi.filterDatas(data.head['head'])});
                            // //设置表体数据
                            // props.cardTable.setTableData(moduleid, requestApi.filterDatas(data.bodys[moduleid]));
                            // 设置表头数据
                            updataFormData(props, 'head', requestApi.filterDatas(data.head['head']));
                            // 设置表体数据
                            updatacardTableData(props, moduleid, requestApi.filterDatas(data.bodys[moduleid]));
                            // BTM 性能优化，变更页面数据更新方法
                            let billdatas = props.createExtCardData(window.presetVar.pageId, 'head',bodyarr);
                            //requestApi.handleLoadDataResDada(props.meta.getMeta(), {data:billdatas},props);
                        }
                    })
                
                //编辑后事件控制字段可编辑性需要放到valuechange之后
                let currentrow_paytarget = props.cardTable.getValByKeyAndRowId(moduleId, changedrows[0].rowid, 'paytarget')
                if (currentrow_paytarget){
                    let currentrow_paytargetvalue = currentrow_paytarget.value
                        //控制表体收款对象相关字段的可编辑性
                    let editablekeys = []
                    let uneditablekeys = []
                    if ("0" == currentrow_paytargetvalue){
                        editablekeys = ['receiver','skyhzh']
                        uneditablekeys = ['hbbm','hbbm_v','customer','customer_v','custaccount']
                    }else if("1" == currentrow_paytargetvalue){
                        editablekeys = ['hbbm','hbbm_v','custaccount']
                        uneditablekeys = ['receiver','skyhzh','customer','customer_v']
                    }else if("2" == currentrow_paytargetvalue){
                        editablekeys = ['customer','customer_v','custaccount']
                        uneditablekeys = ['receiver','skyhzh','hbbm','hbbm_v']
                    }
                    props.cardTable.setEditableByRowId(moduleId, changedrows[0].rowid, editablekeys, true)
                    props.cardTable.setEditableByRowId(moduleId, changedrows[0].rowid, uneditablekeys, false)
                }
                // 编辑后，本币汇率、本币汇率日期、本币汇率来源日期编辑性设置
                // 新增汇率适配逻辑
                let currentrow_bzbm = props.cardTable.getValByKeyAndRowId(moduleId, changedrows[0].rowid, 'bzbm')
                let rate_category = props.cardTable.getValByKeyAndRowId(moduleId, changedrows[0].rowid, 'zzhllx.rate_category')
                zzhllxLogic(currentrow_bzbm,rate_category,'body',props,moduleId,changedrows[0].rowid)
            }
            break;
    }
};